<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>任务详情</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>
      
      <!-- 任务基本信息 -->
      <el-descriptions title="任务信息" :column="2" border>
        <el-descriptions-item label="任务ID">{{ taskInfo.photoTaskId }}</el-descriptions-item>
        <el-descriptions-item label="价格">{{ taskInfo.money }}</el-descriptions-item>
        <el-descriptions-item label="打印状态">
          <el-tag :type="taskInfo.printStatus === '1' ? 'success' : 'warning'">
            {{ taskInfo.printStatus === '1' ? '已打印' : '未打印' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="打印尺寸">{{ taskInfo.printSize }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ taskInfo.address }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(taskInfo.createTime) }}</el-descriptions-item>
      </el-descriptions>

      <!-- 照片管理区域 -->
      <div style="margin-top: 20px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
          <h3>关联照片 ({{ photosList.length }})</h3>
          <el-button type="primary" size="small" @click="handleAddPhoto" v-hasPermi="['print:photo:add']">
            添加照片
          </el-button>
        </div>

        <el-table v-loading="photosLoading" :data="photosList" style="width: 100%">
          <el-table-column label="照片ID" align="center" prop="singlePhotoId" width="100" />
          <el-table-column label="图片预览" align="center" width="150">
            <template slot-scope="scope">
              <el-image 
                style="width: 100px; height: 100px"
                :src="scope.row.imgUrl"
                :preview-src-list="[scope.row.imgUrl]"
                fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column label="图片地址" align="center" prop="imgUrl" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeletePhoto(scope.row)"
                v-hasPermi="['print:photo:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 添加照片对话框 -->
    <el-dialog title="添加照片" :visible.sync="addPhotoOpen" width="600px" append-to-body>
      <el-form ref="photoForm" :model="photoForm" :rules="photoRules" label-width="80px">
        <el-form-item label="图片上传" prop="imgUrl">
          <el-upload
            ref="photoUpload"
            :action="uploadAction"
            :headers="uploadHeaders"
            :data="uploadData"
            :file-list="photoFileList"
            :auto-upload="false"
            :on-change="handlePhotoFileChange"
            :on-remove="handlePhotoFileRemove"
            :before-upload="beforePhotoUpload"
            :limit="1"
            accept="image/*"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
        
        <!-- 图片预览区域 -->
        <el-form-item label="图片预览" v-if="photoPreviewImage">
          <div class="image-preview-container">
            <div class="image-preview-item">
              <el-image 
                :src="photoPreviewImage" 
                :preview-src-list="[photoPreviewImage]"
                fit="cover"
                style="width: 200px; height: 200px; border-radius: 8px;"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPhotoForm" :loading="photoUploadLoading">确 定</el-button>
        <el-button @click="cancelPhoto">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPrint, getPhotosByTaskId, addPhotosToTask } from "@/api/print/print"
import { delPhoto } from "@/api/print/photo"
import { uploadImage } from "@/api/print/upload"

export default {
  name: "PrintDetail",
  data() {
    return {
      // 任务ID
      photoTaskId: null,
      // 任务信息
      taskInfo: {},
      // 照片列表
      photosList: [],
      // 照片加载状态
      photosLoading: false,
      // 添加照片对话框
      addPhotoOpen: false,
      // 照片表单
      photoForm: {
        imgUrl: ''
      },
      // 照片表单校验
      photoRules: {
        imgUrl: [
          { required: true, message: "图片地址不能为空", trigger: "blur" }
        ]
      },
      // 上传相关
      uploadAction: "#",
      uploadHeaders: {},
      uploadData: {},
      photoFileList: [],
      photoPreviewImage: null,
      photoUploadLoading: false
    }
  },
  created() {
    this.photoTaskId = this.$route.query.photoTaskId
    this.getTaskInfo()
    this.getPhotosList()
  },
  methods: {
    /** 获取任务信息 */
    getTaskInfo() {
      getPrint(this.photoTaskId).then(response => {
        this.taskInfo = response.data
      })
    },
    /** 获取照片列表 */
    getPhotosList() {
      this.photosLoading = true
      getPhotosByTaskId(this.photoTaskId).then(response => {
        this.photosList = response.data
        this.photosLoading = false
      })
    },
    /** 返回上一页 */
    goBack() {
      this.$router.go(-1)
    },
    /** 添加照片 */
    handleAddPhoto() {
      this.photoForm = {
        imgUrl: ''
      }
      this.photoFileList = []
      this.photoPreviewImage = null
      this.addPhotoOpen = true
    },
    /** 取消添加照片 */
    cancelPhoto() {
      this.addPhotoOpen = false
      this.resetPhotoForm()
    },
    /** 重置照片表单 */
    resetPhotoForm() {
      this.photoForm = {
        imgUrl: ''
      }
      this.photoFileList = []
      this.photoPreviewImage = null
      this.resetForm("photoForm")
    },
    /** 文件改变事件 */
    handlePhotoFileChange(file, fileList) {
      this.photoFileList = fileList
      if (fileList.length > 0) {
        this.uploadPhotoFile(file.raw)
      }
    },
    /** 文件移除事件 */
    handlePhotoFileRemove(file, fileList) {
      this.photoFileList = fileList
      this.photoPreviewImage = null
    },
    /** 上传前验证 */
    beforePhotoUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        return false
      }
      return false // 阻止自动上传
    },
    /** 上传照片文件 */
    uploadPhotoFile(file) {
      this.photoUploadLoading = true
      uploadImage(file).then(response => {
        if (response.code === 200) {
          this.photoForm.imgUrl = response.data.originalUrl
          this.photoPreviewImage = response.data.originalUrl
          this.$message.success('上传成功')
        } else {
          this.$message.error(response.msg || '上传失败')
        }
      }).catch(error => {
        this.$message.error('上传失败: ' + error.message)
      }).finally(() => {
        this.photoUploadLoading = false
      })
    },
    /** 提交照片表单 */
    submitPhotoForm() {
      this.$refs["photoForm"].validate(valid => {
        if (valid) {
          const photos = [this.photoForm]
          addPhotosToTask(this.photoTaskId, photos).then(response => {
            this.$modal.msgSuccess("添加成功")
            this.addPhotoOpen = false
            this.getPhotosList()
          })
        }
      })
    },
    /** 删除照片 */
    handleDeletePhoto(row) {
      this.$modal.confirm('是否确认删除该照片？').then(function() {
        return delPhoto(row.singlePhotoId)
      }).then(() => {
        this.getPhotosList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: 20px;
}

.image-preview-container {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.image-preview-item {
  text-align: center;
}
</style> 